<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import {useRouter} from "vue-router";
import api from "@/api/index.js";
import store from "@/store/index.js";


const username = ref('');
const password = ref('');
const email = ref('');
const router = useRouter();
const handleRegister = () => {
  api.register({
    username: username.value,
    password: password.value,
    email: email.value
  }).then(resp => {
    console.log(resp.data)
    store.commit('SET_USER', resp.data.user)
    localStorage.setItem('token', resp.data.token)
    localStorage.setItem('user', resp.data.user)
    console.log('注册信息:', username.value, password.value, email.value);
    ElMessage.success('注册成功！');
    router.push('/login')
  }).catch(e => {
    ElMessage.error("注册失败"+e)
  })


};
</script>

<template>
  <div class="register-container">
    <div style="padding: 50px">
      <h1>注册，加入知识的海洋</h1>
    </div>
    <transition name="fade">
      <el-card class="register-form">
        <h2>注册</h2>
        <el-form @submit.prevent="handleRegister">
          <el-form-item label="用户名">
            <el-input v-model="username" placeholder="请输入用户名" required />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="email" type="email" placeholder="请输入邮箱" required />
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="password" type="password" placeholder="请输入密码" required />
          </el-form-item>
          <el-form-item>
            <el-button type="success" native-type="submit" style="width: 100%;">注册</el-button>
          </el-form-item>
          <el-link type="primary" @click="router.push('/login')">已有账号？去登录</el-link>
        </el-form>
      </el-card>
    </transition>
  </div>
</template>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80vh;
}

.register-form {
  background: white;
  padding: 2rem;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  width: 300px;
}

.form-group {
  margin-bottom: 1rem;
}

label {
  display: block;
  margin-bottom: 0.5rem;
}

input {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #ccc;
  border-radius: 4px;
}

button {
  width: 100%;
  padding: 0.5rem;
  background-color: #a2dd1b;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #89b50d;
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s;
}

.fade-enter, .fade-leave-to {
  opacity: 0;
}
</style>